helpers.py 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790
  1. import os
  2. import pkgutil
  3. import socket
  4. import sys
  5. import typing as t
  6. import warnings
  7. from datetime import datetime
  8. from functools import lru_cache
  9. from functools import update_wrapper
  10. from threading import RLock
  11. import werkzeug.utils
  12. from werkzeug.routing import BuildError
  13. from werkzeug.urls import url_quote
  14. from .globals import _app_ctx_stack
  15. from .globals import _request_ctx_stack
  16. from .globals import current_app
  17. from .globals import request
  18. from .globals import session
  19. from .signals import message_flashed
  20. if t.TYPE_CHECKING:
  21. from .wrappers import Response
  22. def get_env() -> str:
  23. """Get the environment the app is running in, indicated by the
  24. :envvar:`FLASK_ENV` environment variable. The default is
  25. ``'production'``.
  26. """
  27. return os.environ.get("FLASK_ENV") or "production"
  28. def get_debug_flag() -> bool:
  29. """Get whether debug mode should be enabled for the app, indicated
  30. by the :envvar:`FLASK_DEBUG` environment variable. The default is
  31. ``True`` if :func:`.get_env` returns ``'development'``, or ``False``
  32. otherwise.
  33. """
  34. val = os.environ.get("FLASK_DEBUG")
  35. if not val:
  36. return get_env() == "development"
  37. return val.lower() not in ("0", "false", "no")
  38. def get_load_dotenv(default: bool = True) -> bool:
  39. """Get whether the user has disabled loading dotenv files by setting
  40. :envvar:`FLASK_SKIP_DOTENV`. The default is ``True``, load the
  41. files.
  42. :param default: What to return if the env var isn't set.
  43. """
  44. val = os.environ.get("FLASK_SKIP_DOTENV")
  45. if not val:
  46. return default
  47. return val.lower() in ("0", "false", "no")
  48. def stream_with_context(
  49. generator_or_function: t.Union[
  50. t.Iterator[t.AnyStr], t.Callable[..., t.Iterator[t.AnyStr]]
  51. ]
  52. ) -> t.Iterator[t.AnyStr]:
  53. """Request contexts disappear when the response is started on the server.
  54. This is done for efficiency reasons and to make it less likely to encounter
  55. memory leaks with badly written WSGI middlewares. The downside is that if
  56. you are using streamed responses, the generator cannot access request bound
  57. information any more.
  58. This function however can help you keep the context around for longer::
  59. from flask import stream_with_context, request, Response
  60. @app.route('/stream')
  61. def streamed_response():
  62. @stream_with_context
  63. def generate():
  64. yield 'Hello '
  65. yield request.args['name']
  66. yield '!'
  67. return Response(generate())
  68. Alternatively it can also be used around a specific generator::
  69. from flask import stream_with_context, request, Response
  70. @app.route('/stream')
  71. def streamed_response():
  72. def generate():
  73. yield 'Hello '
  74. yield request.args['name']
  75. yield '!'
  76. return Response(stream_with_context(generate()))
  77. .. versionadded:: 0.9
  78. """
  79. try:
  80. gen = iter(generator_or_function) # type: ignore
  81. except TypeError:
  82. def decorator(*args: t.Any, **kwargs: t.Any) -> t.Any:
  83. gen = generator_or_function(*args, **kwargs) # type: ignore
  84. return stream_with_context(gen)
  85. return update_wrapper(decorator, generator_or_function) # type: ignore
  86. def generator() -> t.Generator:
  87. ctx = _request_ctx_stack.top
  88. if ctx is None:
  89. raise RuntimeError(
  90. "Attempted to stream with context but "
  91. "there was no context in the first place to keep around."
  92. )
  93. with ctx:
  94. # Dummy sentinel. Has to be inside the context block or we're
  95. # not actually keeping the context around.
  96. yield None
  97. # The try/finally is here so that if someone passes a WSGI level
  98. # iterator in we're still running the cleanup logic. Generators
  99. # don't need that because they are closed on their destruction
  100. # automatically.
  101. try:
  102. yield from gen
  103. finally:
  104. if hasattr(gen, "close"):
  105. gen.close() # type: ignore
  106. # The trick is to start the generator. Then the code execution runs until
  107. # the first dummy None is yielded at which point the context was already
  108. # pushed. This item is discarded. Then when the iteration continues the
  109. # real generator is executed.
  110. wrapped_g = generator()
  111. next(wrapped_g)
  112. return wrapped_g
  113. def make_response(*args: t.Any) -> "Response":
  114. """Sometimes it is necessary to set additional headers in a view. Because
  115. views do not have to return response objects but can return a value that
  116. is converted into a response object by Flask itself, it becomes tricky to
  117. add headers to it. This function can be called instead of using a return
  118. and you will get a response object which you can use to attach headers.
  119. If view looked like this and you want to add a new header::
  120. def index():
  121. return render_template('index.html', foo=42)
  122. You can now do something like this::
  123. def index():
  124. response = make_response(render_template('index.html', foo=42))
  125. response.headers['X-Parachutes'] = 'parachutes are cool'
  126. return response
  127. This function accepts the very same arguments you can return from a
  128. view function. This for example creates a response with a 404 error
  129. code::
  130. response = make_response(render_template('not_found.html'), 404)
  131. The other use case of this function is to force the return value of a
  132. view function into a response which is helpful with view
  133. decorators::
  134. response = make_response(view_function())
  135. response.headers['X-Parachutes'] = 'parachutes are cool'
  136. Internally this function does the following things:
  137. - if no arguments are passed, it creates a new response argument
  138. - if one argument is passed, :meth:`flask.Flask.make_response`
  139. is invoked with it.
  140. - if more than one argument is passed, the arguments are passed
  141. to the :meth:`flask.Flask.make_response` function as tuple.
  142. .. versionadded:: 0.6
  143. """
  144. if not args:
  145. return current_app.response_class()
  146. if len(args) == 1:
  147. args = args[0]
  148. return current_app.make_response(args) # type: ignore
  149. def url_for(endpoint: str, **values: t.Any) -> str:
  150. """Generates a URL to the given endpoint with the method provided.
  151. Variable arguments that are unknown to the target endpoint are appended
  152. to the generated URL as query arguments. If the value of a query argument
  153. is ``None``, the whole pair is skipped. In case blueprints are active
  154. you can shortcut references to the same blueprint by prefixing the
  155. local endpoint with a dot (``.``).
  156. This will reference the index function local to the current blueprint::
  157. url_for('.index')
  158. See :ref:`url-building`.
  159. Configuration values ``APPLICATION_ROOT`` and ``SERVER_NAME`` are only used when
  160. generating URLs outside of a request context.
  161. To integrate applications, :class:`Flask` has a hook to intercept URL build
  162. errors through :attr:`Flask.url_build_error_handlers`. The `url_for`
  163. function results in a :exc:`~werkzeug.routing.BuildError` when the current
  164. app does not have a URL for the given endpoint and values. When it does, the
  165. :data:`~flask.current_app` calls its :attr:`~Flask.url_build_error_handlers` if
  166. it is not ``None``, which can return a string to use as the result of
  167. `url_for` (instead of `url_for`'s default to raise the
  168. :exc:`~werkzeug.routing.BuildError` exception) or re-raise the exception.
  169. An example::
  170. def external_url_handler(error, endpoint, values):
  171. "Looks up an external URL when `url_for` cannot build a URL."
  172. # This is an example of hooking the build_error_handler.
  173. # Here, lookup_url is some utility function you've built
  174. # which looks up the endpoint in some external URL registry.
  175. url = lookup_url(endpoint, **values)
  176. if url is None:
  177. # External lookup did not have a URL.
  178. # Re-raise the BuildError, in context of original traceback.
  179. exc_type, exc_value, tb = sys.exc_info()
  180. if exc_value is error:
  181. raise exc_type(exc_value).with_traceback(tb)
  182. else:
  183. raise error
  184. # url_for will use this result, instead of raising BuildError.
  185. return url
  186. app.url_build_error_handlers.append(external_url_handler)
  187. Here, `error` is the instance of :exc:`~werkzeug.routing.BuildError`, and
  188. `endpoint` and `values` are the arguments passed into `url_for`. Note
  189. that this is for building URLs outside the current application, and not for
  190. handling 404 NotFound errors.
  191. .. versionadded:: 0.10
  192. The `_scheme` parameter was added.
  193. .. versionadded:: 0.9
  194. The `_anchor` and `_method` parameters were added.
  195. .. versionadded:: 0.9
  196. Calls :meth:`Flask.handle_build_error` on
  197. :exc:`~werkzeug.routing.BuildError`.
  198. :param endpoint: the endpoint of the URL (name of the function)
  199. :param values: the variable arguments of the URL rule
  200. :param _external: if set to ``True``, an absolute URL is generated. Server
  201. address can be changed via ``SERVER_NAME`` configuration variable which
  202. falls back to the `Host` header, then to the IP and port of the request.
  203. :param _scheme: a string specifying the desired URL scheme. The `_external`
  204. parameter must be set to ``True`` or a :exc:`ValueError` is raised. The default
  205. behavior uses the same scheme as the current request, or
  206. :data:`PREFERRED_URL_SCHEME` if no request context is available.
  207. This also can be set to an empty string to build protocol-relative
  208. URLs.
  209. :param _anchor: if provided this is added as anchor to the URL.
  210. :param _method: if provided this explicitly specifies an HTTP method.
  211. """
  212. appctx = _app_ctx_stack.top
  213. reqctx = _request_ctx_stack.top
  214. if appctx is None:
  215. raise RuntimeError(
  216. "Attempted to generate a URL without the application context being"
  217. " pushed. This has to be executed when application context is"
  218. " available."
  219. )
  220. # If request specific information is available we have some extra
  221. # features that support "relative" URLs.
  222. if reqctx is not None:
  223. url_adapter = reqctx.url_adapter
  224. blueprint_name = request.blueprint
  225. if endpoint[:1] == ".":
  226. if blueprint_name is not None:
  227. endpoint = f"{blueprint_name}{endpoint}"
  228. else:
  229. endpoint = endpoint[1:]
  230. external = values.pop("_external", False)
  231. # Otherwise go with the url adapter from the appctx and make
  232. # the URLs external by default.
  233. else:
  234. url_adapter = appctx.url_adapter
  235. if url_adapter is None:
  236. raise RuntimeError(
  237. "Application was not able to create a URL adapter for request"
  238. " independent URL generation. You might be able to fix this by"
  239. " setting the SERVER_NAME config variable."
  240. )
  241. external = values.pop("_external", True)
  242. anchor = values.pop("_anchor", None)
  243. method = values.pop("_method", None)
  244. scheme = values.pop("_scheme", None)
  245. appctx.app.inject_url_defaults(endpoint, values)
  246. # This is not the best way to deal with this but currently the
  247. # underlying Werkzeug router does not support overriding the scheme on
  248. # a per build call basis.
  249. old_scheme = None
  250. if scheme is not None:
  251. if not external:
  252. raise ValueError("When specifying _scheme, _external must be True")
  253. old_scheme = url_adapter.url_scheme
  254. url_adapter.url_scheme = scheme
  255. try:
  256. try:
  257. rv = url_adapter.build(
  258. endpoint, values, method=method, force_external=external
  259. )
  260. finally:
  261. if old_scheme is not None:
  262. url_adapter.url_scheme = old_scheme
  263. except BuildError as error:
  264. # We need to inject the values again so that the app callback can
  265. # deal with that sort of stuff.
  266. values["_external"] = external
  267. values["_anchor"] = anchor
  268. values["_method"] = method
  269. values["_scheme"] = scheme
  270. return appctx.app.handle_url_build_error(error, endpoint, values)
  271. if anchor is not None:
  272. rv += f"#{url_quote(anchor)}"
  273. return rv
  274. def get_template_attribute(template_name: str, attribute: str) -> t.Any:
  275. """Loads a macro (or variable) a template exports. This can be used to
  276. invoke a macro from within Python code. If you for example have a
  277. template named :file:`_cider.html` with the following contents:
  278. .. sourcecode:: html+jinja
  279. {% macro hello(name) %}Hello {{ name }}!{% endmacro %}
  280. You can access this from Python code like this::
  281. hello = get_template_attribute('_cider.html', 'hello')
  282. return hello('World')
  283. .. versionadded:: 0.2
  284. :param template_name: the name of the template
  285. :param attribute: the name of the variable of macro to access
  286. """
  287. return getattr(current_app.jinja_env.get_template(template_name).module, attribute)
  288. def flash(message: str, category: str = "message") -> None:
  289. """Flashes a message to the next request. In order to remove the
  290. flashed message from the session and to display it to the user,
  291. the template has to call :func:`get_flashed_messages`.
  292. .. versionchanged:: 0.3
  293. `category` parameter added.
  294. :param message: the message to be flashed.
  295. :param category: the category for the message. The following values
  296. are recommended: ``'message'`` for any kind of message,
  297. ``'error'`` for errors, ``'info'`` for information
  298. messages and ``'warning'`` for warnings. However any
  299. kind of string can be used as category.
  300. """
  301. # Original implementation:
  302. #
  303. # session.setdefault('_flashes', []).append((category, message))
  304. #
  305. # This assumed that changes made to mutable structures in the session are
  306. # always in sync with the session object, which is not true for session
  307. # implementations that use external storage for keeping their keys/values.
  308. flashes = session.get("_flashes", [])
  309. flashes.append((category, message))
  310. session["_flashes"] = flashes
  311. message_flashed.send(
  312. current_app._get_current_object(), # type: ignore
  313. message=message,
  314. category=category,
  315. )
  316. def get_flashed_messages(
  317. with_categories: bool = False, category_filter: t.Iterable[str] = ()
  318. ) -> t.Union[t.List[str], t.List[t.Tuple[str, str]]]:
  319. """Pulls all flashed messages from the session and returns them.
  320. Further calls in the same request to the function will return
  321. the same messages. By default just the messages are returned,
  322. but when `with_categories` is set to ``True``, the return value will
  323. be a list of tuples in the form ``(category, message)`` instead.
  324. Filter the flashed messages to one or more categories by providing those
  325. categories in `category_filter`. This allows rendering categories in
  326. separate html blocks. The `with_categories` and `category_filter`
  327. arguments are distinct:
  328. * `with_categories` controls whether categories are returned with message
  329. text (``True`` gives a tuple, where ``False`` gives just the message text).
  330. * `category_filter` filters the messages down to only those matching the
  331. provided categories.
  332. See :doc:`/patterns/flashing` for examples.
  333. .. versionchanged:: 0.3
  334. `with_categories` parameter added.
  335. .. versionchanged:: 0.9
  336. `category_filter` parameter added.
  337. :param with_categories: set to ``True`` to also receive categories.
  338. :param category_filter: filter of categories to limit return values. Only
  339. categories in the list will be returned.
  340. """
  341. flashes = _request_ctx_stack.top.flashes
  342. if flashes is None:
  343. _request_ctx_stack.top.flashes = flashes = (
  344. session.pop("_flashes") if "_flashes" in session else []
  345. )
  346. if category_filter:
  347. flashes = list(filter(lambda f: f[0] in category_filter, flashes))
  348. if not with_categories:
  349. return [x[1] for x in flashes]
  350. return flashes
  351. def _prepare_send_file_kwargs(
  352. download_name: t.Optional[str] = None,
  353. attachment_filename: t.Optional[str] = None,
  354. etag: t.Optional[t.Union[bool, str]] = None,
  355. add_etags: t.Optional[t.Union[bool]] = None,
  356. max_age: t.Optional[
  357. t.Union[int, t.Callable[[t.Optional[str]], t.Optional[int]]]
  358. ] = None,
  359. cache_timeout: t.Optional[int] = None,
  360. **kwargs: t.Any,
  361. ) -> t.Dict[str, t.Any]:
  362. if attachment_filename is not None:
  363. warnings.warn(
  364. "The 'attachment_filename' parameter has been renamed to"
  365. " 'download_name'. The old name will be removed in Flask"
  366. " 2.2.",
  367. DeprecationWarning,
  368. stacklevel=3,
  369. )
  370. download_name = attachment_filename
  371. if cache_timeout is not None:
  372. warnings.warn(
  373. "The 'cache_timeout' parameter has been renamed to"
  374. " 'max_age'. The old name will be removed in Flask 2.2.",
  375. DeprecationWarning,
  376. stacklevel=3,
  377. )
  378. max_age = cache_timeout
  379. if add_etags is not None:
  380. warnings.warn(
  381. "The 'add_etags' parameter has been renamed to 'etag'. The"
  382. " old name will be removed in Flask 2.2.",
  383. DeprecationWarning,
  384. stacklevel=3,
  385. )
  386. etag = add_etags
  387. if max_age is None:
  388. max_age = current_app.get_send_file_max_age
  389. kwargs.update(
  390. environ=request.environ,
  391. download_name=download_name,
  392. etag=etag,
  393. max_age=max_age,
  394. use_x_sendfile=current_app.use_x_sendfile,
  395. response_class=current_app.response_class,
  396. _root_path=current_app.root_path, # type: ignore
  397. )
  398. return kwargs
  399. def send_file(
  400. path_or_file: t.Union[os.PathLike, str, t.BinaryIO],
  401. mimetype: t.Optional[str] = None,
  402. as_attachment: bool = False,
  403. download_name: t.Optional[str] = None,
  404. attachment_filename: t.Optional[str] = None,
  405. conditional: bool = True,
  406. etag: t.Union[bool, str] = True,
  407. add_etags: t.Optional[bool] = None,
  408. last_modified: t.Optional[t.Union[datetime, int, float]] = None,
  409. max_age: t.Optional[
  410. t.Union[int, t.Callable[[t.Optional[str]], t.Optional[int]]]
  411. ] = None,
  412. cache_timeout: t.Optional[int] = None,
  413. ):
  414. """Send the contents of a file to the client.
  415. The first argument can be a file path or a file-like object. Paths
  416. are preferred in most cases because Werkzeug can manage the file and
  417. get extra information from the path. Passing a file-like object
  418. requires that the file is opened in binary mode, and is mostly
  419. useful when building a file in memory with :class:`io.BytesIO`.
  420. Never pass file paths provided by a user. The path is assumed to be
  421. trusted, so a user could craft a path to access a file you didn't
  422. intend. Use :func:`send_from_directory` to safely serve
  423. user-requested paths from within a directory.
  424. If the WSGI server sets a ``file_wrapper`` in ``environ``, it is
  425. used, otherwise Werkzeug's built-in wrapper is used. Alternatively,
  426. if the HTTP server supports ``X-Sendfile``, configuring Flask with
  427. ``USE_X_SENDFILE = True`` will tell the server to send the given
  428. path, which is much more efficient than reading it in Python.
  429. :param path_or_file: The path to the file to send, relative to the
  430. current working directory if a relative path is given.
  431. Alternatively, a file-like object opened in binary mode. Make
  432. sure the file pointer is seeked to the start of the data.
  433. :param mimetype: The MIME type to send for the file. If not
  434. provided, it will try to detect it from the file name.
  435. :param as_attachment: Indicate to a browser that it should offer to
  436. save the file instead of displaying it.
  437. :param download_name: The default name browsers will use when saving
  438. the file. Defaults to the passed file name.
  439. :param conditional: Enable conditional and range responses based on
  440. request headers. Requires passing a file path and ``environ``.
  441. :param etag: Calculate an ETag for the file, which requires passing
  442. a file path. Can also be a string to use instead.
  443. :param last_modified: The last modified time to send for the file,
  444. in seconds. If not provided, it will try to detect it from the
  445. file path.
  446. :param max_age: How long the client should cache the file, in
  447. seconds. If set, ``Cache-Control`` will be ``public``, otherwise
  448. it will be ``no-cache`` to prefer conditional caching.
  449. .. versionchanged:: 2.0
  450. ``download_name`` replaces the ``attachment_filename``
  451. parameter. If ``as_attachment=False``, it is passed with
  452. ``Content-Disposition: inline`` instead.
  453. .. versionchanged:: 2.0
  454. ``max_age`` replaces the ``cache_timeout`` parameter.
  455. ``conditional`` is enabled and ``max_age`` is not set by
  456. default.
  457. .. versionchanged:: 2.0
  458. ``etag`` replaces the ``add_etags`` parameter. It can be a
  459. string to use instead of generating one.
  460. .. versionchanged:: 2.0
  461. Passing a file-like object that inherits from
  462. :class:`~io.TextIOBase` will raise a :exc:`ValueError` rather
  463. than sending an empty file.
  464. .. versionadded:: 2.0
  465. Moved the implementation to Werkzeug. This is now a wrapper to
  466. pass some Flask-specific arguments.
  467. .. versionchanged:: 1.1
  468. ``filename`` may be a :class:`~os.PathLike` object.
  469. .. versionchanged:: 1.1
  470. Passing a :class:`~io.BytesIO` object supports range requests.
  471. .. versionchanged:: 1.0.3
  472. Filenames are encoded with ASCII instead of Latin-1 for broader
  473. compatibility with WSGI servers.
  474. .. versionchanged:: 1.0
  475. UTF-8 filenames as specified in :rfc:`2231` are supported.
  476. .. versionchanged:: 0.12
  477. The filename is no longer automatically inferred from file
  478. objects. If you want to use automatic MIME and etag support,
  479. pass a filename via ``filename_or_fp`` or
  480. ``attachment_filename``.
  481. .. versionchanged:: 0.12
  482. ``attachment_filename`` is preferred over ``filename`` for MIME
  483. detection.
  484. .. versionchanged:: 0.9
  485. ``cache_timeout`` defaults to
  486. :meth:`Flask.get_send_file_max_age`.
  487. .. versionchanged:: 0.7
  488. MIME guessing and etag support for file-like objects was
  489. deprecated because it was unreliable. Pass a filename if you are
  490. able to, otherwise attach an etag yourself.
  491. .. versionchanged:: 0.5
  492. The ``add_etags``, ``cache_timeout`` and ``conditional``
  493. parameters were added. The default behavior is to add etags.
  494. .. versionadded:: 0.2
  495. """
  496. return werkzeug.utils.send_file(
  497. **_prepare_send_file_kwargs(
  498. path_or_file=path_or_file,
  499. environ=request.environ,
  500. mimetype=mimetype,
  501. as_attachment=as_attachment,
  502. download_name=download_name,
  503. attachment_filename=attachment_filename,
  504. conditional=conditional,
  505. etag=etag,
  506. add_etags=add_etags,
  507. last_modified=last_modified,
  508. max_age=max_age,
  509. cache_timeout=cache_timeout,
  510. )
  511. )
  512. def send_from_directory(
  513. directory: t.Union[os.PathLike, str],
  514. path: t.Union[os.PathLike, str],
  515. filename: t.Optional[str] = None,
  516. **kwargs: t.Any,
  517. ) -> "Response":
  518. """Send a file from within a directory using :func:`send_file`.
  519. .. code-block:: python
  520. @app.route("/uploads/<path:name>")
  521. def download_file(name):
  522. return send_from_directory(
  523. app.config['UPLOAD_FOLDER'], name, as_attachment=True
  524. )
  525. This is a secure way to serve files from a folder, such as static
  526. files or uploads. Uses :func:`~werkzeug.security.safe_join` to
  527. ensure the path coming from the client is not maliciously crafted to
  528. point outside the specified directory.
  529. If the final path does not point to an existing regular file,
  530. raises a 404 :exc:`~werkzeug.exceptions.NotFound` error.
  531. :param directory: The directory that ``path`` must be located under.
  532. :param path: The path to the file to send, relative to
  533. ``directory``.
  534. :param kwargs: Arguments to pass to :func:`send_file`.
  535. .. versionchanged:: 2.0
  536. ``path`` replaces the ``filename`` parameter.
  537. .. versionadded:: 2.0
  538. Moved the implementation to Werkzeug. This is now a wrapper to
  539. pass some Flask-specific arguments.
  540. .. versionadded:: 0.5
  541. """
  542. if filename is not None:
  543. warnings.warn(
  544. "The 'filename' parameter has been renamed to 'path'. The"
  545. " old name will be removed in Flask 2.2.",
  546. DeprecationWarning,
  547. stacklevel=2,
  548. )
  549. path = filename
  550. return werkzeug.utils.send_from_directory( # type: ignore
  551. directory, path, **_prepare_send_file_kwargs(**kwargs)
  552. )
  553. def get_root_path(import_name: str) -> str:
  554. """Find the root path of a package, or the path that contains a
  555. module. If it cannot be found, returns the current working
  556. directory.
  557. Not to be confused with the value returned by :func:`find_package`.
  558. :meta private:
  559. """
  560. # Module already imported and has a file attribute. Use that first.
  561. mod = sys.modules.get(import_name)
  562. if mod is not None and hasattr(mod, "__file__") and mod.__file__ is not None:
  563. return os.path.dirname(os.path.abspath(mod.__file__))
  564. # Next attempt: check the loader.
  565. loader = pkgutil.get_loader(import_name)
  566. # Loader does not exist or we're referring to an unloaded main
  567. # module or a main module without path (interactive sessions), go
  568. # with the current working directory.
  569. if loader is None or import_name == "__main__":
  570. return os.getcwd()
  571. if hasattr(loader, "get_filename"):
  572. filepath = loader.get_filename(import_name) # type: ignore
  573. else:
  574. # Fall back to imports.
  575. __import__(import_name)
  576. mod = sys.modules[import_name]
  577. filepath = getattr(mod, "__file__", None)
  578. # If we don't have a file path it might be because it is a
  579. # namespace package. In this case pick the root path from the
  580. # first module that is contained in the package.
  581. if filepath is None:
  582. raise RuntimeError(
  583. "No root path can be found for the provided module"
  584. f" {import_name!r}. This can happen because the module"
  585. " came from an import hook that does not provide file"
  586. " name information or because it's a namespace package."
  587. " In this case the root path needs to be explicitly"
  588. " provided."
  589. )
  590. # filepath is import_name.py for a module, or __init__.py for a package.
  591. return os.path.dirname(os.path.abspath(filepath))
  592. class locked_cached_property(werkzeug.utils.cached_property):
  593. """A :func:`property` that is only evaluated once. Like
  594. :class:`werkzeug.utils.cached_property` except access uses a lock
  595. for thread safety.
  596. .. versionchanged:: 2.0
  597. Inherits from Werkzeug's ``cached_property`` (and ``property``).
  598. """
  599. def __init__(
  600. self,
  601. fget: t.Callable[[t.Any], t.Any],
  602. name: t.Optional[str] = None,
  603. doc: t.Optional[str] = None,
  604. ) -> None:
  605. super().__init__(fget, name=name, doc=doc)
  606. self.lock = RLock()
  607. def __get__(self, obj: object, type: type = None) -> t.Any: # type: ignore
  608. if obj is None:
  609. return self
  610. with self.lock:
  611. return super().__get__(obj, type=type)
  612. def __set__(self, obj: object, value: t.Any) -> None:
  613. with self.lock:
  614. super().__set__(obj, value)
  615. def __delete__(self, obj: object) -> None:
  616. with self.lock:
  617. super().__delete__(obj)
  618. def is_ip(value: str) -> bool:
  619. """Determine if the given string is an IP address.
  620. :param value: value to check
  621. :type value: str
  622. :return: True if string is an IP address
  623. :rtype: bool
  624. """
  625. for family in (socket.AF_INET, socket.AF_INET6):
  626. try:
  627. socket.inet_pton(family, value)
  628. except OSError:
  629. pass
  630. else:
  631. return True
  632. return False
  633. @lru_cache(maxsize=None)
  634. def _split_blueprint_path(name: str) -> t.List[str]:
  635. out: t.List[str] = [name]
  636. if "." in name:
  637. out.extend(_split_blueprint_path(name.rpartition(".")[0]))
  638. return out